<template>
  <el-row class="login-container" justify="center" align="middle">
    <el-card style="max-width: 480px;">
      <template #header>
        <div class="card-header">
          <img :src="imgUrl" alt="">
        </div>
      </template>
      <div class="jump-link">
        <el-link type="primary" @click="handleChange">{{ formType ? '返回登录':'注册账号' }}</el-link>
      </div>
      <el-form 
        ref="loginFormRef"
        :model="loginForm" 
        :rules="rules"
        >
        <el-form-item prop="userName">
          <el-input v-model="loginForm.userName" 
          :prefix-icon="UserFilled"
          placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item prop="passWord">
          <el-input v-model="loginForm.passWord" type="password" 
          :prefix-icon="Lock"
          placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item prop="validCode" v-if="formType">
          <el-input v-model="loginForm.validCode" 
          :prefix-icon="Lock"
          placeholder="请输入验证码">
          <template #append>
            <span @click="countdownChange">{{ countdown.validText }}</span>
          </template>
        </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(loginFormRef)" :style="{width: '100%'}">
            {{ formType ? '注册账号' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-row>
</template>

<script setup>
import { ref, reactive,computed, toRaw }from 'vue'
import {getCode, userAuthentication, userLogin,menuPermissions } from '@/api/index.js'
import { UserFilled, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
// pzadmin/src/assets/background-bg.jpeg
const imgUrl = new URL('../../../src/assets/background-bg.jpeg',import.meta.url).href

const router = useRouter()
// 登录表单数据
const loginForm = reactive({
  userName:'',
  passWord:'',
  validCode:''
})
// 登录或者注册的状态 0登录 1注册
const formType = ref(0)

// 表单验证规则-账号校验
const validetaUser = (rule,value,callback)=>{
  const phoneReg = /^1[3-9]\d{9}$/
  if(!value){
    callback(new Error('请输入手机号'))
  }else if(!phoneReg.test(value)){
    callback(new Error('手机号格式不正确'))
  }else{
    callback()
  }
}
// 表单验证规则-密码校验
const validatePass = (rule,value,callback)=>{
  if(!value){
    callback(new Error('密码不能为空'))

  }else{
    const passReg = /^[a-zA-Z0-9]{6,16}$/
    passReg.test(value) ? callback(): callback(new Error('密码格式不正确'))
  }
}

const rules= reactive({
  userName:[    {validator: validetaUser , trigger:'blur' }  ],
  passWord:[{validator: validatePass , trigger:'blur' }]
})

// 切换登录或者注册页面
const handleChange=()=>{
 formType.value = formType.value ? 0 : 1
}
// 验证码
const countdown = reactive({
  validText:'获取验证码',
  time:10
})
// 倒计时

let flag = false
let timeId
const countdownChange =()=>{
  if(flag) return
  const phoneReg = /^1[3-9]\d{9}$/
  if(!loginForm.userName|| !phoneReg.test(loginForm.userName)){
    return ElMessage({
      type:'warning',
      message:'请检查手机号'
    })
  }
  timeId = setInterval(()=>{
    if(countdown.time <=0){
      countdown.validText = '获取验证码'
      countdown.time = 10
      flag = false
      clearInterval(timeId)
    }else{
      countdown.validText = `${countdown.time}秒后重新获取`
      countdown.time -=1
    }
  },1000)
  flag = true
  getCode({tel: loginForm.userName}).then(( {data})=>{
    if(data.code === 10000){
      ElMessage({
        type:'success',
        message:data.msg
      })
    }else{
      ElMessage({
        type:'error',
        message:data.message
      })
    }
  }).catch(err=>{
    console.error(err)
  })
}

// 获取表单组件
const loginFormRef = ref(null)
const store = useStore()
const routerList = computed(()=>store.state.menu.routerList)
// 提交表单
const submitForm = async (formEl)=>{
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // console.log('submit!',loginForm)
      if(formType.value){
        // 注册
        userAuthentication(loginForm).then(({data})=>{
          if(data.code ===10000){
            ElMessage({
              type:'success',
              message:'注册成功，请登录'
            })
            formType.value = 0 // 提交注册后切换到登录
          }
        })
      }else{
        // 登录
        userLogin(loginForm).then(({data})=>{
          if(data.code === 10000){
            ElMessage({
              type:'success',
              message:'登录成功'
            })
            localStorage.setItem('pz_token',data.data.token)
            localStorage.setItem('pz_userInfo',JSON.stringify(data.data.userInfo))
            menuPermissions().then(({data})=>{
              if(data.code === 10000){
                store.commit('dynamicMenu',data.data)
                // 教学版
                toRaw(routerList.value).forEach(item => {
                  router.addRoute('main',item)
                });
                // console.log('router',router)
                // console.log('routerList',routerList)
                setTimeout(() => {
                  router.push('/')
                }, 10);
              }
            })
          }
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
function addXieLine(routerPath){
  if(!routerPath.path.startsWith('/')){
    routerPath.path = '/'+routerPath.path
  }
}
</script>

<style lang="less" scoped>
:deep(.el-card__header) {
  padding: 0;
}
.login-container {
  height: 100%;
  .card-header{
    background-color: #899fe1;
    img{
      width: 430px;
    }
  }
  .jump-link{
    text-align: right;
    margin-bottom: 10px;
  }
}
</style>